package cn.onekit.android;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import cn.onekit.CALLBACK;
import cn.onekit.DIALOG;

@SuppressLint("SimpleDateFormat")
public class ACTIVITY extends FragmentActivity {

	public static Context context;
	private static File outFile;
	private static CALLBACK<Bitmap> imageCallback;
	private static final int IMAGE_CAPTURE = 100;
	private static final int VIDEO_CAPTURE = 200;
	private static final int GET_CONTENT = 300;

	protected final int getStringID(String resID) {
		return getResources().getIdentifier(resID, "string", getPackageName());
	}

	protected final int getRawID(String resID) {
		return getResources().getIdentifier(resID, "raw", getPackageName());
	}

	final static float scale() {
		return context.getResources().getDisplayMetrics().density;
	}

	public static int dp2px(float dp) {
		return (int) (dp * scale() + 0.5f);
	}

	public static int px2dp(float px) {
		return (int) (px / scale() + 0.5f);
	}
/*
	public static int dp2sp(float dp) {
		return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				context.getResources().getDisplayMetrics()));
	}*/

	public static int sp2px(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}
	public static int px2sp(Context context, float pxValue){
		 float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (pxValue / fontScale + 0.5f);
		
	}
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		context = this;
	}

	@Override
	protected void onResume() {
		super.onResume();
		context = this;
		//MESSAGE.send("[Application]Resume", null, null);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		context = this;
	}

	@Override
	protected void onPause() {
		super.onPause();
		context = this;
	}

	protected static void openCamera(CALLBACK<Bitmap> callback) {
		imageCallback = callback;
		String state = Environment.getExternalStorageState();
		try {
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				File outDir = new File(String.format("%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s",
						Environment.getExternalStorageDirectory(), java.io.File.separator, "Android",
						java.io.File.separator, "data", java.io.File.separator, ACTIVITY.context.getPackageName(),
						java.io.File.separator, "Image"));
				if (!outDir.exists()) {
					outDir.mkdirs();
				}
				outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);	
				intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
				((Activity) ACTIVITY.context).startActivityForResult(intent, IMAGE_CAPTURE);
			} else {
				DIALOG.toast("���������������������SD���");
			}
		} catch (ActivityNotFoundException e) {
			DIALOG.toast("������������������");
		}
	}

	protected static void openGallery(CALLBACK<Bitmap> callback) {
		imageCallback = callback;
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.setAction(Intent.ACTION_GET_CONTENT);
		/* ������������������������������ */
		((Activity) ACTIVITY.context).startActivityForResult(intent, GET_CONTENT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case IMAGE_CAPTURE: {
			Bundle bundle = data.getExtras();
			if (bundle != null) {
				imageCallback.run(false, (Bitmap) bundle.get("data"));
			}

			break;
		}
		case VIDEO_CAPTURE: {
			if (resultCode == RESULT_OK) {
				Uri uriVideo = data.getData();
				Cursor cursor = this.getContentResolver().query(uriVideo, null, null, null, null);
				if (cursor.moveToNext()) {
					/* _data������������������������ ���_display_name������������ */
					String strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
					Toast.makeText(this, strVideoPath, Toast.LENGTH_SHORT).show();
					String videoPath = "111111113.3gp";
					Date now = new Date();
					SimpleDateFormat f2 = new SimpleDateFormat("yyyyMMdd");
					SimpleDateFormat f3 = new SimpleDateFormat("HHmmss");
					videoPath = f2.format(now) + "_" + f3.format(now) + ".3gp";
					File file = new File(strVideoPath);
					String pFile = file.getParentFile().getPath() + "/";
					String newPath = pFile + videoPath;
					file.renameTo(new File(newPath));
					DIALOG.toast("���������������������������" + newPath);
				}
			}
			break;
		}
		case GET_CONTENT: {
			if (data == null) {
				return;
			}
			ContentResolver resolver = getContentResolver();
			Uri originalUri = data.getData();
			Bitmap image;
			try {
				image = MediaStore.Images.Media.getBitmap(resolver, originalUri);
				imageCallback.run(false, image);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
		default:
			break;
		}

	}
/*
	@SuppressWarnings("resource")
	private static long getFileSize(File file) {
		long size = 0;
		try {
			if (file.exists()) {
				FileInputStream fis = null;
				fis = new FileInputStream(file);
				size = fis.available();
			} else {
				file.createNewFile();
				Log.e("������������������", "���������������!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return size;
	}*/

	protected void fullscreen() {
		// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		// getActionBar().hide();
		this.getActionBar().hide();
		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);//���������������
		// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);//���������������
	}  
	
	 public boolean isAppOnForeground() {  
         // Returns a list of application processes that are running on the  
         // device  
            
         ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);  
         String packageName = getApplicationContext().getPackageName();  

         List<RunningAppProcessInfo> appProcesses = activityManager  
                         .getRunningAppProcesses();  
         if (appProcesses == null)  
                 return false;  

         for (RunningAppProcessInfo appProcess : appProcesses) {  
                 // The name of the process that this object is associated with.  
                 if (appProcess.processName.equals(packageName)  
                                 && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
                         return true;  
                 }  
         }  

         return false;  
	 }
}